<template>
  <div class="sec-main">
    <div class="search-container">
      <sec-form
        labelWidth="60px"
        :searchBox="{ span: 6 }"
        :ruleForm="ruleForm"
        :formData="formData"
        :optionData="optionData"
        @reset="reset"
        @submitForm="submitForm"
      >
      </sec-form>
    </div>

    <div class="table-container">
      <div class="new-file">
        <el-button type="text" size="large" @click="centerDialogVisible = true" icon="el-icon-plus">{{
          $t("新建")
        }}</el-button>
      </div>

      <sec-table :tableData="tableData" :tableCol="tableCol"></sec-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        background
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :layout="layout"
        :total="totalSize"
      >
      </el-pagination>
    </div>

    <el-drawer title="详情" :visible.sync="drawer.table" direction="rtl" size="60%" :modal="false">
      <!-- 任务详情 开始 -->
      <touch-detail
        v-if="drawer.table"
        :touchId="touchId"
        :detailData="touchData"
        :needRequest="needRequest"
      ></touch-detail>
      <el-descriptions
        class="detail-descriptions"
        contentClassName="content-class"
        labelClassName="label-class"
        :title="this.$t('子任务信息')"
        :column="1"
        border
      >
        <template slot="extra">
          <el-button
            v-show="touchData.status == 4"
            type="text"
            size="medium"
            @click="flushSubTaskDetail('click')"
            style="padding: 0 5px"
          >
            <i class="el-icon-refresh"></i
          ></el-button>
        </template>
        <!-- TODO 任务可点击查看详情 -->
        <el-descriptions-item :span="1" :label="this.$t('子任务数量')">
          <span>{{ subTaskDetail.statusCount }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="1" :label="this.$t('子任务状态')">
          <span>{{ subTaskDetail.info }}</span>
        </el-descriptions-item>
        <el-descriptions-item :span="1" :label="this.$t('失败原因')">
          <span>{{ subTaskDetail.errorInfo }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <br />
      <div class="detail-bottom">
        <div class="detail-button">
          <el-button slot="reference" @click="startTouch" :disabled="touchData.status != 2" type="primary"
            >{{ this.$t("开始触达") }}
          </el-button>
        </div>
        <div class="detail-button">
          <el-tooltip class="item" effect="dark" :content="$t('向自己发一份触达，用以预览效果')" placement="top-start">
            <el-button type="primary" @click="previewTouchSource">{{ this.$t("预览任务") }}</el-button>
          </el-tooltip>
        </div>
      </div>
    </el-drawer>
    <el-dialog :title="$t('请选择触达渠道')" :visible.sync="centerDialogVisible" width="20%">
      <div style="display: flex; justify-content: center">
        <span slot="footer" class="dialog-footer">
          <el-button @click="createTouchTask('d-chat')">{{ $t("D-Chat") }}</el-button>
          <el-button @click="createTouchTask('e-mail')">{{ $t("邮件") }}</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TouchDetail from "views/touch/detail.vue";
import { paginationMixin } from "@/mixins/pagination";
import Cookies from "js-cookie";
import {
  touchListApi,
  detailTaskApi,
  touchStartApi,
  commitTouchApi,
  previewTouchApi,
  touchDetailSubTaskApi,
} from "api/dataCenter.js";

export default {
  name: "space",
  components: { TouchDetail },
  mixins: [paginationMixin],
  props: {},
  data() {
    var that = this;
    return {
      centerDialogVisible: false,

      spaceId: null,
      markdownEditor: {
        defaultOpen: "preview",
      },

      //用户名称数据
      name: "",
      status: {
        已生成: 0,
        发送中: 0,
        发送异常: 0,
        已发送: 0,
        发送成功: 0,
        发送失败: 0,
        已操作: 0,
        已通知: 0,
        通知失败: 0,
        关闭: 0,
      },
      subTaskDetail: {},
      selectRow: {},
      touchId: "",
      needRequest: false,
      ruleForm: {
        title: "",
        creator: "",
        updateStatus: true,
      },
      optionData: {
        creator: [],
      },
      formData: [
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("消息标题"),
          prop: "title",
          span: 8,
        },
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("创建人"),
          prop: "creator",
          span: 8,

          optionProps: {
            value: "userId",
            label: (item) => {
              return `${item.userId} -- ${item.userName}`;
            },
          },
        },
      ],
      tableData: [],
      tableCol: [
        { label: this.$t("ID"), prop: "id" },
        { label: this.$t("空间ID"), prop: "spaceId" },
        {
          label: this.$t("消息标题"),
          prop: "title",
        },
        // {
        //   label: this.$t("消息内容"),
        //   prop: "content",
        // },
        {
          label: this.$t("消息渠道"),
          prop: "msgChannel",
          formatter: (row, column, cellValue, index) => {
            return this.utils.getDicLabel("msgChannel", row.msgChannel);
          },
        },
        {
          label: this.$t("创建人"),
          prop: "creator",
        },
        { label: this.$t("发送账号"), prop: "sender" },
        // {
        //   label: this.$t("接收者（多名）"),
        //   prop: "receiver",
        // },
        {
          label: this.$t("状态"),
          prop: "status",
          formatter: (row, column, cellValue, index) => {
            return this.utils.getDicLabel("status", row.status);
          },
        },
        {
          label: this.$t("是否排他"),
          prop: "exclusive",
          formatter: (row, column, cellValue, index) => {
            return this.utils.getDicLabel("exclusive", row.exclusive);
          },
        },
        { label: this.$t("审核时间"), prop: "reviewTime" },
        { label: this.$t("创建时间"), prop: "createTime", width: 150 },
        {
          type: "operation",
          label: "操作",
          width: 150,
          children: [
            {
              label: "编辑",
              click: (data) => {
                this.editClick(data);
              },
              disabled: (data) => {
                return !(data.row.status == 0 || data.row.status == 3);
              },
            },
            // todo 提交后编辑按钮与提交按钮都要失效
            {
              label: "提审",
              disabled: (data) => {
                let { row } = data;
                // console.log(that.name);
                return !(data.row.status == 0);
              },
              click: (data) => {
                let {
                  id,
                  // 标题
                  title,
                  // 内容
                  content,
                  // 接收者
                  receiver,
                  // 渠道
                  msgChannel,
                  // 0 不排他，1 排他
                  exclusive,
                  // 模版id
                  templateId,
                  // 消息主体
                  msgAccountId,
                  // dc 表单id
                  dcFormId,
                  // 模版变量
                  variables,
                  // 回调地址
                  notifyUrl,
                  //跟崔id
                  followId,
                  // dc 会话id
                  vChannelId,
                } = data.row;
                this.commitClick(id);
              },
            },
            {
              label: "详情",
              click: (data) => {
                this.detailClick(data);
              },
            },
          ],
        },
      ],
      // 抽屉新数据
      drawer: {
        table: false,
        dialog: false,
        loading: false,
        tableData: [],
        contentData: {},
      },
      touchData: {},
      receiverDialogVisible: false,
      contentDialogVisible: false,
    };
  },
  created() {
    // 获取用户名信息
    this.name = Cookies.get("_kylin_username");
  },
  mounted() {
    this.spaceId = this.$route.params.spaceId;
    //初始化页面
    if (!this.spaceId) {
      this.message.warning({ message: "链接有误，错误标签已关闭" });
      this.$store.dispatch("tagsView/delView", this.$route).then(({ visitedViews }) => {});
      this.$router.push({ path: "/home" });
    } else {
      this.initPage();
    }
  },
  methods: {
    initPage() {
      this.getSpaceData(); //初始化表格数据
    },
    // 再此编辑
    reedit() {
      //复制一份存起来
      this.$router.push({
        path: "/space/touch/insert" + "?id=" + this.touchData.id + "&spaceId=" + this.spaceId,
      });
    },
    //获取表格数据
    getSpaceData() {
      //打开loading
      let loading = this.openLoading(".sec-main");
      touchListApi(
        {
          pageNum: this.page,
          pageSize: this.pageSize,
          requestData: {
            spaceId: this.spaceId,
            title: this.ruleForm.title,
            creator: this.ruleForm.creator,
          },
        },
        {
          spaceId: this.spaceId,
        },
      ).then((res) => {
        // console.log("[ res ] >", res);
        loading.close();
        if (res.data) {
          let { list, pageNum, pageSize, pages, total } = res.data;
          this.tableData = list;
          // console.log(this.tableData);
          this.totalSize = total;
        }
      });
    },
    //创建触达任务
    createTouchTask(data) {
      this.$emit("create", data);
      this.centerDialogVisible = false;
    },
    // 新建test
    setUpClickTest() {
      this.$router.push({ path: "/space/touch/insert", query: { spaceId: this.spaceId } });
    },
    // 搜索
    submitForm() {
      this.page = 1;
      this.getSpaceData();
    },

    //编辑
    editClick({ row }) {
      this.$emit("edit", row);
    },
    commitClick(id) {
      commitTouchApi(
        {
          requestData: id,
        },
        {
          spaceId: this.spaceId,
        },
      ).then((res) => {
        this.initPage();
      });
    },

    //重置
    reset() {
      this.page = 1; //每次点击重置的时候都是第一页
      this.getSpaceData();
    },
    // 预览
    previewTouchSource() {
      let {
        // 渠道 DC：1 邮件：2
        msgChannel,
      } = this.touchData;
      previewTouchApi(
        {
          requestData: {
            id: this.touchData.id,
          },
        },
        {
          spaceId: this.spaceId,
        },
      ).then((res) => {
        let msg = msgChannel == 1 ? this.$t("预览发送成功，请到DC查看详情") : this.$t("预览发送成功，请到邮箱查看详情");
        if (res.code !== 0) return;
        this.message.success({
          message: msg,
        });
      });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getSpaceData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getSpaceData();
    },
    //详情信息
    detailClick(data) {
      let { id, sender, receiver, content, notifyUrl } = data.row;
      this.selectRow = data;
      console.log(this.selectRow);

      detailTaskApi({
        requestData: id,
      }).then((res) => {
        // console.log("taskStatus res", res);
        this.drawer.table = true;
        this.needRequest = false;
        this.touchData = res.data;
      });
      this.flushSubTaskDetail();
    },
    //刷新子任务信息
    flushSubTaskDetail(type) {
      touchDetailSubTaskApi({
        requestData: this.selectRow.row.id,
      }).then((res) => {
        if (res.code === 0) {
          let { count, info, statusCount, errorInfo } = res.data;
          this.subTaskDetail = {
            count: count ? count : "-",
            info: info ? info : "-",
            statusCount: statusCount ? statusCount : "-",
            errorInfo: errorInfo ? errorInfo : "-",
          };
          if (type == "click") {
            this.message.success({ message: this.$t("子任务信息刷新成功") });
          }
        }
      });
    },
    startTouch() {
      this.utils.$confirm({ content: "确定触达吗？" }, () => {
        touchStartApi(
          {
            requestData: this.touchData.id,
          },
          {
            spaceId: this.spaceId,
          },
        ).then((res) => {
          // console.log(res.data);
          this.initPage();
          this.touchId = `${this.touchData.id}`;
          this.needRequest = true;
          if (res.code === 0) {
            this.detailClick(this.selectRow);
            this.message.success({ message: this.$t("开始触达，详见子任务信息") });
          }
        });
      });
    },
  },

  computed: {},
  watch: {},
};
</script>

<style scoped lang="scss">
// ::v-deep .el-drawer__body {
//   padding: 0 20px;
// }
::v-deep .el-drawer__body {
  padding: 0 20px !important;
}
.detail-descriptions {
  margin-bottom: 10px;
  ::v-deep.el-descriptions__header {
    justify-content: flex-start !important;
  }
}
::v-deep .content-class {
  word-wrap: break-word;
  word-break: break-all;
}
::v-deep .label-class {
  width: 100px;
}
.detail-bottom {
  display: flex;
  justify-content: center;
  .detail-button {
    padding: 15px 10px 10px 10px;
  }
}
</style>
